//
//  SLManualAnimationController.m
//  Objective-C
//
//  Created by S_Line on 2018/7/3.
//  Copyright © 2018年 S_Line. All rights reserved.
//

#import "SLManualAnimationController.h"

@interface SLManualAnimationController ()

@property (nonatomic, weak) UIView *containerView;
@property (nonatomic, strong) CALayer *doorLayer;

@end

@implementation SLManualAnimationController

- (void)initNavBar {
    self.navTitle = @"";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initNavBar];
    
    [self initView];
}

- (void)initView {
    UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, kNavigationBarHeight, kScreenWidth, kScreenHeight - kNavigationBarHeight - kSafeBottomMargin)];
    self.containerView = containerView;
    [self.view addSubview:containerView];
    
    // add the door
    CGFloat doorW = 120.0;
    CGFloat doorH = 144.0;
    CALayer *doorLayer = [CALayer layer];
    self.doorLayer = doorLayer;
    doorLayer.frame = CGRectMake(0, 0, doorW, doorH);
    doorLayer.position = CGPointMake((kScreenWidth - doorW) / 2.0, containerView.bounds.size.height / 2.0);
    doorLayer.anchorPoint = CGPointMake(0.0, 0.5);
    doorLayer.contents = (__bridge id)[UIImage imageNamed:@"caDoor"].CGImage;
    [self.containerView.layer addSublayer:doorLayer];
    
    // apply perspective transform
    CATransform3D perspective = CATransform3DIdentity;
    perspective.m34 = 1.0 / 500.0;
    self.containerView.layer.sublayerTransform = perspective;
    
    // add pan gesture recognizer to handle swipes
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    [self.view addGestureRecognizer:pan];
    
    // pause all layer animations
    self.doorLayer.speed = 0.0;
    
    // apply swinging animation (which won't play because layer is paused)
    CABasicAnimation *animation = [CABasicAnimation animation];
    animation.keyPath = @"transform.rotation.y";
    animation.toValue = @(-M_PI_2);
    animation.duration = 1.0;
    [self.doorLayer addAnimation:animation forKey:nil];
    
    doorLayer.timeOffset = 0.5;
}

- (void)pan:(UIPanGestureRecognizer *)pan {
    // get horizotal component of pan gesture
    CGFloat x = [pan translationInView:self.view].x;
    
    // convert from points to animation duration
    // using a reasonable scale factor
    x /= 200.0;
    // update timeOffset and clamp result
    CFTimeInterval timeOffset = self.doorLayer.timeOffset;
    SLog(@"before: %f", timeOffset);
    timeOffset = MIN(0.999, MAX(0.0, timeOffset - x));
    SLog(@"after: %f", timeOffset);
    self.doorLayer.timeOffset = timeOffset;
    
    // reset pan gesture
    [pan setTranslation:CGPointZero inView:self.view];
}

@end
